//
//  YBSendMessageViewController.m
//  GongXinDangJian
//
//  Created by apple on 17/12/6.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YBSendMessageViewController.h"
#import "YBNormalWaterLayoutView.h"
#import "YBNewChoosePeopleViewController.h"
#import "PlaceholderTextView.h"
#import "ZJSIPotoView.h"
#import "ZLPhotoActionSheet.h"
#import "STPhotoBroswer.h"
#import "YBPeopleInfoModel.h"
#import "LCustomAlertView.h"

@interface YBSendMessageViewController ()<YBNewChoosePeopleViewControllerDelegate , UITextFieldDelegate , LPChooseYearAndMonthAndDayAndHourAndMinuteDelegate , ZJSIPotoViewDelegate , LCustomAlertDelegate , YBNormalWaterLayoutViewDelegate>
{
    NSInteger _index;/**< 标记图片数组的长度 */
    NSInteger _deleImageIndex;/**< 删除图片的下标 */
}
/**  back  */
@property (strong, nonatomic) UIScrollView  *backScrollView;

@property (nonatomic , strong) UIButton * sendButton;

@property (nonatomic , strong) YBNormalWaterLayoutView * selectView;

@property (nonatomic , strong) NSArray * dataArray;

@property (nonatomic , strong) UITextField * titleTextField;

@property (nonatomic , strong) PlaceholderTextView * contentTextView;

@property (nonatomic , strong) UITextField * effectTimeTextField;

@property (nonatomic , strong) UITextField * overdueTimeTextField;

@property (nonatomic , strong) UITextField * currentSelectTextField;

@property (nonatomic , strong) LPChooseYearAndMonthAndDayAndHourAndMinuteView * pickTime;

@property (nonatomic , strong) ZJSIPotoView * potoView;
/** 图片数组 */
@property (nonatomic, strong) NSMutableArray *imageArray;

@property (nonatomic , strong) JCAlertView * jcAlertView;

@property (nonatomic , assign) NSInteger currentDeleteIndex;
@end

@implementation YBSendMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = @[];
    // Do any additional setup after loading the view.
    self.currentSelectTextField = nil;
    self.currentDeleteIndex = 0;
    self.titlelabel.text = @"消息发送";
    [self ybInitUserInterface];
}

-(void)ybInitUserInterface{
    [self.view addSubview:self.backScrollView];
    
    UIView * contentView = [[UIView alloc]initWithFrame:CGRectMake(0, [UIScreen zj_screenHeight] - ItemHeight * 160, [UIScreen zj_screenWith], ItemHeight * 160)];
    contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:contentView];
    [contentView addSubview:self.sendButton];
    
    [self.backScrollView addSubview:self.selectView];
    
    UIView * tempView = [[UIView alloc]initWithFrame:CGRectMake(0, ItemHeight * 450, [UIScreen zj_screenWith], ItemHeight * 20)];
    tempView.backgroundColor = [UIColor themeGrayColor];
    [self.backScrollView addSubview:tempView];
    
    [self.backScrollView addSubview:self.titleTextField];
    
    [self.backScrollView addSubview:self.contentTextView];
    
    [self.backScrollView addSubview:self.effectTimeTextField];
    [self.backScrollView addSubview:self.overdueTimeTextField];
    
    [self.backScrollView addSubview:self.potoView];
    
    self.potoView.sd_layout
    .topSpaceToView(self.overdueTimeTextField, ItemHeight * 20)
    .leftSpaceToView(self.backScrollView, 0)
    .rightSpaceToView(self.backScrollView, 0)
    .heightIs(self.potoView.height);
    
    [self.backScrollView setupAutoContentSizeWithBottomView:self.potoView bottomMargin:ItemHeight * 50];
}

-(void)option_sendButton:(UIButton *)sender{
    if (self.selectView.dataArray.count == 0) {
        [YJProgressHUD showSuccess:@"请选择发布对象" inview:self.view];
        return;
    }
    if (self.titleTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请输入消息标题" inview:self.view];
        return;
    }
    if (self.contentTextView.text.length == 0) {
        [YJProgressHUD showSuccess:@"请输入消息内容" inview:self.view];
        return;
    }
    if (self.effectTimeTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请选择生效时间" inview:self.view];
        return;
    }
    if (self.overdueTimeTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请选择过期时间" inview:self.view];
        return;
    }
    NSTimeInterval effectTime = [[NSDateFormatter dateHourAndMintueWithString:self.effectTimeTextField.text] timeIntervalSince1970];
    NSTimeInterval overTime = [[NSDateFormatter dateHourAndMintueWithString:self.overdueTimeTextField.text] timeIntervalSince1970];
    if (effectTime > overTime) {
        [YJProgressHUD showSuccess:@"过期时间必须大于生效时间" inview:self.view];
        return;
    }
    [self senderNetWorking];
}


- (void)senderNetWorking{
    NetWorkUpLoadModel *loadModel = [NetWorkUpLoadModel new];
    loadModel.UPLOAD_FILES = self.imageArray;
    loadModel.ACCOUNT_ID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID;
    loadModel.ACCOUNT_NAME = ZJUSERINFORMODEL.ORG_ACCOUNT.USER_NAME;
    loadModel.TITLE = self.titleTextField.text;
    loadModel.CONTENT = self.contentTextView.text;
    loadModel.MSG_START_TIME = self.effectTimeTextField.text;
    loadModel.MSG_END_TIME = self.overdueTimeTextField.text;
    NSMutableArray * tempArray = [NSMutableArray array];
    for (YBPeopleInfoModel * model in self.selectView.dataArray) {
        NSDictionary * dic = @{@"ID" : model.ID , @"ACCOUNT_NAME" : model.NAME , @"F_DEPT_NAME" : model.F_DEPT_NAME};
        [tempArray addObject:dic];
    }
    loadModel.SEND_USERS = [ToolClass getjsonStringFromArray:[tempArray copy]];
    [YJProgressHUD showMessage:@"发送中..." duration:10 view:[UIApplication sharedApplication].keyWindow];
    [NetWorkingManager uploadingWithXMLString:@"miit.action.MiitMsgAction[publishMsg]" Parameter:loadModel Success:^(id object) {
        [YJProgressHUD hide];
        if ([object[@"STATE"] isEqualToString:@"20000"]) {
            [YJProgressHUD showSuccess:@"发送成功" inview:self.view];

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            [YJProgressHUD showSuccess:@"发送失败" inview:self.view];
        }
    } Fail:^(id object) {
        [YJProgressHUD hide];
        [YJProgressHUD showSuccess:@"网络错误" inview:self.view];
    }];
}


-(void)option_selectButton:(UIButton *)sender{
    [self.titleTextField endEditing:YES];
    [self.contentTextView endEditing:YES];
    YBNewChoosePeopleViewController * vc = [[YBNewChoosePeopleViewController alloc]init];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)didClickDeleteButtonWithIndex:(NSInteger)index{
    self.currentDeleteIndex = index;
    YBPeopleInfoModel * tempModel = self.dataArray[index];
    LCustomAlertView *alert = [[LCustomAlertView alloc] initWithFrame:self.view.bounds alertMessage:[NSString stringWithFormat:@"是否删除 %@-%@" , [ToolClass returnNoNullStringWithString:tempModel.F_DEPT_NAME] , [ToolClass returnNoNullStringWithString:tempModel.NAME]] titlesArray:@[@"取消",@"确定"]];
    alert.delegate = self;
    self.jcAlertView = [[JCAlertView alloc]initWithCustomView:alert dismissWhenTouchedBackground:YES];
    [self.jcAlertView show];
}


#pragma mark - LCustomAlertDelegate
- (void)lCustomAlertWithView:(LCustomAlertView *)view index:(NSInteger)index{
    if (index == 1) {
        /**  确认  */
        NSMutableArray * tempArray = [self.dataArray mutableCopy];
        [tempArray removeObjectAtIndex:self.currentDeleteIndex];
        self.dataArray = [tempArray copy];
        [self.selectView deleteItemAtIndex:self.currentDeleteIndex];
    }
    [self.jcAlertView dismissWithCompletion:nil];
}



-(void)ybClickEnsureButtonWithCurrentSelectArray:(NSArray *)currentSelectArray
{
    NSMutableArray * tempArray = [NSMutableArray array];
    for (YBPeopleInfoModel * model in self.dataArray) {
        [tempArray addObject:model.ACCOUNT_ID];
    }
    NSMutableArray * addArray = [self.dataArray mutableCopy];
    for (YBPeopleInfoModel * tempModel in currentSelectArray) {
        if (![tempArray containsObject:tempModel.ACCOUNT_ID]) {
            [addArray addObject:tempModel];
        }
    }
    self.dataArray = [addArray copy];
    self.selectView.dataArray = [addArray copy];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.effectTimeTextField] || [textField isEqual:self.overdueTimeTextField]) {
        self.currentSelectTextField = textField;
        [self.contentTextView endEditing:YES];
        [self.titleTextField endEditing:YES];
        [self.pickTime showCurrentTime];
        return NO;
    }
    return YES;
}




- (void)ChooseYearAndMonthAndDayAndHourAndMinuteWithTitle:(NSString * )string{
    if (self.currentSelectTextField) {
        self.currentSelectTextField.text = string;
    }
    //选择年月日返回代理方法
}


#pragma mark - ZJSIPotoViewDelegate(图片加好) 协议方法
- (void)ZJSIPotoViewDelegate_addPotoClick{
    [self.view endEditing:YES];
    if (self.imageArray.count == 9) {
        [YJProgressHUD showMessage:@"最多选择9张图片" inView:self.view];
    }
    else{
        _index = self.imageArray.count;
        //图片多选模块
        ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
        //设置最大选择数量
        actionSheet.maxSelectCount = 9 - self.imageArray.count;
        //设置预览图最大数目
        actionSheet.maxPreviewCount = 20;
        __weak typeof(self) weakSelf = self;
        [actionSheet showWithSender:self animate:YES lastSelectPhotoModels:nil completion:^(NSArray<UIImage *> * _Nonnull selectPhotos, NSArray<ZLSelectPhotoModel *> * _Nonnull selectPhotoModels) {
            
            [selectPhotos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                
                NSData * data = [ToolClass compressionImageWithImage:obj compressionMaxLimit:COMPRESSIONMAXLIMIT];
                NetWorkUploadFileModel *model = [NetWorkUploadFileModel new];
                model.FILE_NAME = [NSString stringWithFormat:@"%@.jpg",[NSDate getCurrentDate]];
                model.FILE_INDEX = [NSString stringWithFormat:@"%ld",(unsigned long)idx];
                model.FILE_PATH = data;
                model.NAME = @"IMG_URL";
                [weakSelf.imageArray addObject:model];
            }];
            _index = self.imageArray.count;
            [weakSelf.potoView updateUI_PotoArray:weakSelf.imageArray];
            weakSelf.potoView.sd_layout
            .topSpaceToView(self.overdueTimeTextField, ItemHeight * 20)
            .leftSpaceToView(self.backScrollView, 0)
            .rightSpaceToView(self.backScrollView, 0)
            .heightIs(self.potoView.height);
            [weakSelf.potoView updateLayout];
            
        }];
    }
    
}

- (void)ZJSIPotoViewDelegate_deletePotoClick_index:(NSInteger)index{
    _deleImageIndex = index;
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否确定删除图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.imageArray removeObjectAtIndex:_deleImageIndex];
        _index = self.imageArray.count;
        [self.potoView updateUI_PotoArray:self.imageArray];
        self.potoView.sd_layout
        .topSpaceToView(self.overdueTimeTextField, ItemHeight * 20)
        .leftSpaceToView(self.backScrollView, 0)
        .rightSpaceToView(self.backScrollView, 0)
        .heightIs(self.potoView.height);
        [self.potoView updateLayout];
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)ZJSIPotoViewDelegate_potoImageClick_index:(NSInteger)index{
    __block NSMutableArray *imageDataArray = [NSMutableArray array];
    [self.imageArray enumerateObjectsUsingBlock:^(NetWorkUploadFileModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *dict = @{@"image":[UIImage imageWithData:obj.FILE_PATH]};
        [imageDataArray addObject:dict];
    }];
    STPhotoBroswer *view = [[STPhotoBroswer alloc]initWithFrame:CGRectMake(0, 0,self.view.width , self.view.height) ImageArray:imageDataArray currentIndex:index];
    [view show];
}



- (UIScrollView *)backScrollView{
    if (!_backScrollView ) {
        _backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0 , navHeight, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] - navHeight - ItemHeight * 160)];
        _backScrollView.showsVerticalScrollIndicator = NO;
        _backScrollView.showsHorizontalScrollIndicator = NO;
        _backScrollView.contentSize = _backScrollView.size;
        _backScrollView.backgroundColor = [UIColor whiteColor];
    }
    return _backScrollView;
    
}

-(UIButton *)sendButton
{
    if (!_sendButton) {
        _sendButton = [ToolClass createButtonWithFrame:CGRectMake(ItemWidth * 100, ItemHeight * 30, [UIScreen zj_screenWith] - ItemWidth * 200, ItemHeight * 100) text:@"发送消息" textColor:[UIColor whiteColor] imageName:@"" font:16];
        _sendButton.backgroundColor = [UIColor themeColor];
        [_sendButton addTarget:self action:@selector(option_sendButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendButton;
}

-(YBNormalWaterLayoutView *)selectView
{
    if (!_selectView) {
        _selectView = [[YBNormalWaterLayoutView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], ItemHeight * 450) title:@"发布对象(0):"];
        [_selectView.selectButton addTarget:self action:@selector(option_selectButton:) forControlEvents:UIControlEventTouchUpInside];
        _selectView.delegate = self;
    }
    return _selectView;
}

-(UITextField *)titleTextField
{
    if (!_titleTextField) {
        _titleTextField = [[UITextField alloc]initWithFrame:CGRectMake(ItemWidth * 30, ItemHeight * 510, [UIScreen zj_screenWith] - ItemWidth * 60, ItemHeight * 80)];
        _titleTextField.backgroundColor = [UIColor themeGrayColor];
        _titleTextField.clipsToBounds = YES;
        _titleTextField.layer.cornerRadius = normalCornerRadius;
        _titleTextField.font = LYPFONT(15);
        _titleTextField.placeholder = @"请输入消息标题";
        _titleTextField.delegate = self;
        _titleTextField.returnKeyType = UIReturnKeyDone;
    }
    return _titleTextField;
}


- (PlaceholderTextView *)contentTextView{
    if (!_contentTextView) {
        _contentTextView = [[PlaceholderTextView alloc]initWithFrame:CGRectMake(ItemWidth * 30, ItemHeight * 610, [UIScreen zj_screenWith] - ItemWidth * 60, ItemHeight * 270)];
        _contentTextView.backgroundColor = [UIColor themeGrayColor];
        _contentTextView.placeholder = @"不得输入任何涉密内容";
        _contentTextView.clipsToBounds = YES;
        _contentTextView.layer.cornerRadius = normalCornerRadius;
        _contentTextView.returnKeyType = UIReturnKeyDone;
        _contentTextView.font = LYPFONT(15);
    }
    return _contentTextView;
}

-(UITextField *)effectTimeTextField
{
    if (!_effectTimeTextField) {
        _effectTimeTextField = [[UITextField alloc]initWithFrame:CGRectMake(ItemWidth * 30, ItemHeight * 900, [UIScreen zj_screenWith] - ItemWidth * 60, ItemHeight * 80)];
        _effectTimeTextField.backgroundColor = [UIColor themeGrayColor];
        _effectTimeTextField.clipsToBounds = YES;
        _effectTimeTextField.layer.cornerRadius = normalCornerRadius;
        _effectTimeTextField.font = LYPFONT(15);
        _effectTimeTextField.placeholder = @"选择生效时间";
        _effectTimeTextField.delegate = self;
        _effectTimeTextField.returnKeyType = UIReturnKeyDone;
    }
    return _effectTimeTextField;
}


-(UITextField *)overdueTimeTextField
{
    if (!_overdueTimeTextField) {
        _overdueTimeTextField = [[UITextField alloc]initWithFrame:CGRectMake(ItemWidth * 30, ItemHeight * 1000, [UIScreen zj_screenWith] - ItemWidth * 60, ItemHeight * 80)];
        _overdueTimeTextField.backgroundColor = [UIColor themeGrayColor];
        _overdueTimeTextField.clipsToBounds = YES;
        _overdueTimeTextField.layer.cornerRadius = normalCornerRadius;
        _overdueTimeTextField.font = LYPFONT(15);
        _overdueTimeTextField.placeholder = @"选择过期时间";
        _overdueTimeTextField.delegate = self;
        _overdueTimeTextField.returnKeyType = UIReturnKeyDone;
    }
    return _overdueTimeTextField;
}

- (LPChooseYearAndMonthAndDayAndHourAndMinuteView *)pickTime{
    if (!_pickTime) {
        _pickTime  = [[LPChooseYearAndMonthAndDayAndHourAndMinuteView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
        _pickTime.delegate = self;
    }
    return _pickTime;
}


- (ZJSIPotoView *)potoView{
    if (_potoView == nil){
        _potoView = [[ZJSIPotoView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 195  * [UIScreen zj_screenHScale]) title:@"不得上传任何涉密图片"];
        [_potoView updateUI_PotoArray:nil];
        _potoView.deletate = self;
        
    }
    return _potoView;
}


-(NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}


@end
